package com.mirstone.jetpackdemo.room;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.mirstone.jetpackdemo.App;
import com.mirstone.jetpackdemo.R;
import com.mirstone.jetpackdemo.databinding.ItemUserBinding;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerHolder> {

    private static final String TAG = "RecyclerAdapter";
    private List<User> users;

    public void update(List<User> users) {
        this.users = users;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        return new RecyclerHolder(ItemUserBinding.inflate(inflater, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerHolder holder, int position) {
        User user = users.get(position);
        if (holder.binding instanceof ItemUserBinding) {
            ItemUserBinding binding = (ItemUserBinding) holder.binding;
            binding.setUser(user);
            binding.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int delete = App.getAppDataBase().userDao().delete(user);
                    Log.d(TAG, "onClick: " + delete);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return users != null ? users.size() : 0;
    }
}
